package com.wjj.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.wjj.common.core.constant.Constants;
import com.wjj.common.core.utils.MapstructUtils;
import com.wjj.common.core.utils.ServletUtils;
import com.wjj.common.core.utils.StringUtils;
import com.wjj.common.core.utils.ip.AddressUtils;
import com.wjj.common.log.event.LogininforEvent;
import com.wjj.common.mybatis.core.page.PageQuery;
import com.wjj.common.mybatis.core.page.TableDataInfo;
import com.wjj.common.satoken.utils.LoginHelper;
import com.wjj.system.domain.SysLogininfor;
import com.wjj.system.domain.bo.SysLogininforBo;
import com.wjj.system.domain.vo.SysClientVo;
import com.wjj.system.domain.vo.SysLogininforVo;
import com.wjj.system.mapper.SysLogininforMapper;
import com.wjj.system.service.ISysClientService;
import com.wjj.system.service.ISysLogininforService;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 系统访问日志情况信息 服务层处理
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Slf4j
@Service
public class SysLogininforServiceImpl extends ServiceImpl<SysLogininforMapper, SysLogininfor> implements ISysLogininforService {

    private final ISysClientService clientService;

    /**
     * 记录登录信息
     *
     * @param logininforEvent 登录事件
     */
    @Async
    @EventListener
    public void recordLogininfor(LogininforEvent logininforEvent) {
        HttpServletRequest request = logininforEvent.getRequest();
        final UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        final String ip = ServletUtils.getClientIP(request);
        // 客户端信息
        String clientId = request.getHeader(LoginHelper.CLIENT_KEY);
        SysClientVo client = null;
        if (StringUtils.isNotBlank(clientId)) {
            client = clientService.queryByClientId(clientId);
        }

        String address = AddressUtils.getRealAddressByIP(ip);
        StringBuilder s = new StringBuilder();
        s.append(getBlock(ip));
        s.append(address);
        s.append(getBlock(logininforEvent.getUsername()));
        s.append(getBlock(logininforEvent.getStatus()));
        s.append(getBlock(logininforEvent.getMessage()));
        // 打印信息到日志
        log.info(s.toString(), logininforEvent.getArgs());
        // 获取客户端操作系统
        String os = userAgent.getOs().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        // 封装对象
        SysLogininforBo logininfor = new SysLogininforBo();
        logininfor.setUserName(logininforEvent.getUsername());
        if (ObjectUtil.isNotNull(client)) {
            logininfor.setClientKey(client.getClientKey());
            logininfor.setDeviceType(client.getDeviceType());
        }
        logininfor.setIpaddr(ip);
        logininfor.setLoginLocation(address);
        logininfor.setBrowser(browser);
        logininfor.setOs(os);
        logininfor.setMsg(logininforEvent.getMessage());
        // 日志状态
        if (StringUtils.equalsAny(logininforEvent.getStatus(), Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) {
            logininfor.setStatus(Constants.SUCCESS);
        } else if (Constants.LOGIN_FAIL.equals(logininforEvent.getStatus())) {
            logininfor.setStatus(Constants.FAIL);
        }
        // 插入数据
        insertLogininfor(logininfor);
    }

    private String getBlock(Object msg) {
        if (msg == null) {
            msg = "";
        }
        return "[" + msg.toString() + "]";
    }

    @Override
    public TableDataInfo<SysLogininforVo> selectPageLogininforList(SysLogininforBo logininfor, PageQuery pageQuery) {
        Map<String, Object> params = logininfor.getParams();
        QueryWrapper qw = QueryWrapper.create()
            .like(SysLogininfor::getIpaddr, logininfor.getIpaddr(), StringUtils.isNotBlank(logininfor.getIpaddr()))
            .eq(SysLogininfor::getStatus, logininfor.getStatus(), StringUtils.isNotBlank(logininfor.getStatus()))
            .like(SysLogininfor::getUserName, logininfor.getStatus(), StringUtils.isNotBlank(logininfor.getUserName()))
            .between(SysLogininfor::getLoginTime, params.get("beginTime"), params.get("endTime"), params.get("beginTime") != null && params.get("endTime") != null);

        if (StringUtils.isBlank(pageQuery.getOrderByColumn())) {
            qw.orderBy(SysLogininfor::getInfoId, false);
        }
        Page<SysLogininfor> page = mapper.paginate(pageQuery.build(), qw);
        Page<SysLogininforVo> resultPage = new Page<>(page.getPageNumber(), page.getPageSize(), page.getTotalRow());
        resultPage.setRecords(MapstructUtils.convert(page.getRecords(), SysLogininforVo.class));
        return TableDataInfo.build(resultPage);
    }

    /**
     * 新增系统登录日志
     *
     * @param bo 访问日志对象
     */
    @Override
    public void insertLogininfor(SysLogininforBo bo) {
        SysLogininfor logininfor = MapstructUtils.convert(bo, SysLogininfor.class);
        logininfor.setLoginTime(new Date());
        mapper.insert(logininfor);
    }

    /**
     * 查询系统登录日志集合
     *
     * @param logininfor 访问日志对象
     * @return 登录记录集合
     */
    @Override
    public List<SysLogininforVo> selectLogininforList(SysLogininforBo logininfor) {
        Map<String, Object> params = logininfor.getParams();
        List<SysLogininfor> sysLogininfors = mapper.selectListByQuery(QueryWrapper.create()
            .like(SysLogininfor::getIpaddr, logininfor.getIpaddr(), StringUtils.isNotBlank(logininfor.getIpaddr()))
            .eq(SysLogininfor::getStatus, logininfor.getStatus(), StringUtils.isNotBlank(logininfor.getStatus()))
            .like(SysLogininfor::getUserName, logininfor.getUserName(), StringUtils.isNotBlank(logininfor.getUserName()))
            .between(SysLogininfor::getLoginTime, params.get("beginTime"), params.get("endTime"), params.get("beginTime") != null && params.get("endTime") != null)
            .orderBy(SysLogininfor::getInfoId, false));

        return MapstructUtils.convert(sysLogininfors, SysLogininforVo.class);
    }

    /**
     * 批量删除系统登录日志
     *
     * @param infoIds 需要删除的登录日志ID
     * @return 结果
     */
    @Override
    public int deleteLogininforByIds(Long[] infoIds) {
        return this.removeByIds(Arrays.asList(infoIds)) ? 1 : 0;
    }

    /**
     * 清空系统登录日志
     */
    @Override
    public void cleanLogininfor() {
        mapper.deleteByQuery(QueryWrapper.create());
    }
}
